#include<sys/wait.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>

int main(){
    pid_t pid;
    int status;

    // 创建子进程
    pid = fork();
    if(pid < 0){
        // fork失败
        perror("fork failed");
        exit(1);
    }

    if(pid == 0){
        // 子进程执行
        sleep(1);
        printf("Child process, pid is %d\n", getpid());
        exit(2);
    }

    if(pid > 0){
        // 父进程执行
       int child_pid =  wait(&status);
       if(child_pid < 0){
            // wait失败
           perror("wait failed");
           exit(1);
       }else{
            // 打印子进程PID
           printf("Child process, pid is %d\n", child_pid);
            // 打印子进程退出状态
           printf("exit code is %x\n",status);
            // 判断子进程是否正常退出
           if(WIFEXITED(status)){
               printf("Child process exit success ,exit code is %d\n", WEXITSTATUS(status));
           }else{
                // 子进程异常退出
               printf("Child process exit failure\n");
           }
        }
    }
}